import { Component, OnInit } from '@angular/core';
import { CommonModule } from '@angular/common';
import { RouterModule, ActivatedRoute, Router } from '@angular/router';
import { FormsModule } from '@angular/forms';
import { HttpClient } from '@angular/common/http';
import { NzMessageModule } from 'ng-zorro-antd/message';
import { NzMessageService } from 'ng-zorro-antd/message';
import { NzTabsModule } from 'ng-zorro-antd/tabs';
import { NzTagModule } from 'ng-zorro-antd/tag';
import { NzButtonModule } from 'ng-zorro-antd/button';
import { NzDividerModule } from 'ng-zorro-antd/divider';

@Component({
  selector: 'app-allocation-detail',
  standalone: true,
  imports: [
    CommonModule,
    RouterModule,
    FormsModule,
    NzMessageModule,
    NzTabsModule,
    NzTagModule,
    NzButtonModule,
    NzDividerModule
  ],
  templateUrl: './allocation-detail.component.html',
  styleUrls: ['./allocation-detail.component.scss']
})
export class AllocationDetailComponent implements OnInit {
  // 调拨单数据
  allocationData: any = {};
  
  // 加载状态
  loading = false;
  
  // 当前活动标签 - 默认显示附件等其他信息
  activeTab = 'basic';
  
  // 附件列表
  attachments: any[] = [];
  
  // 操作记录
  operationLogs: any[] = [];
  
  // 出库记录
  outRecords: any[] = [];
  
  // 入库记录
  inRecords: any[] = [];

  constructor(
    private route: ActivatedRoute,
    private router: Router,
    private http: HttpClient,
    private message: NzMessageService
  ) {}

  ngOnInit(): void {
    // 从URL参数获取调拨单ID
    this.route.paramMap.subscribe(params => {
      const id = params.get('id');
      if (id) {
        // 先检查localStorage中是否有数据
        const storedData = localStorage.getItem('allocationDetailData');
        if (storedData) {
          try {
            const data = JSON.parse(storedData);
            console.log('从localStorage获取到调拨单数据:', data);
            
            // 清除localStorage中的数据，避免影响下次加载
            localStorage.removeItem('allocationDetailData');
            
            // 使用localStorage中的数据
            this.allocationData = data;
            
            // 处理附件数据
            this.processAttachments(data);
            
            // 处理明细数据
            this.processDetails(data);
            
            // 模拟操作记录数据
            this.generateOperationLogs(data);
            
            // 直接加载模拟出入库记录数据
            this.loadMockWarehouseRecords(data);
            
          } catch (error) {
            console.error('解析localStorage数据失败', error);
            // 出错时从API加载
            this.loadAllocationData(id);
          }
        } else {
          // 如果localStorage中没有数据，从API加载
          this.loadAllocationData(id);
        }
      } else {
        this.message.error('无效的调拨单ID');
        this.router.navigate(['/business/inventory/allocation']);
      }
    });
  }

  // 加载调拨单数据
  loadAllocationData(id: string): void {
    this.loading = true;
    this.http.get<any>(`https://localhost:44350/api/app/allocation/${id}`)
      .subscribe({
        next: (response) => {
          console.log('从API获取到调拨单数据:', response);
          this.allocationData = response || {};
          
          // 处理附件数据
          this.processAttachments(response);
          
          // 处理明细数据
          this.processDetails(response);
          
          // 生成操作记录
          this.generateOperationLogs(response);
          
          // 直接加载模拟出入库记录数据，无论调拨单状态如何
          this.loadMockWarehouseRecords(response);
          
          this.loading = false;
        },
        error: (error) => {
          console.error('加载调拨单数据失败', error);
          this.message.error('加载调拨单数据失败: ' + (error.error?.message || '未知错误'));
          this.loading = false;
        }
      });
  }

  // 处理附件数据
  processAttachments(data: any): void {
    if (data.files && data.files.length > 0) {
      console.log('处理附件数据:', data.files);
      this.attachments = data.files.map((file: any) => {
        const fileId = file.id || '';
        return {
          id: this.isValidGuid(fileId) ? fileId : this.generateUUID(),
          name: file.fileName || file.name || '',
          type: file.fileType || file.type || this.getFileExtension(file.fileName || file.name || ''),
          size: file.fileSize || file.size || 0,
          url: file.filePath || file.url || '',
          uploadTime: new Date()
        };
      });
    } else {
      this.attachments = [];
    }
  }
  
  // 处理明细数据
  processDetails(data: any): void {
    // 优先使用details字段
    if (data.details && data.details.length > 0) {
      this.allocationData.details = data.details;
    } 
    // 其次使用allocationItems字段
    else if (data.allocationItems && data.allocationItems.length > 0) {
      this.allocationData.details = data.allocationItems;
    }
    // 最后尝试使用items字段
    else if (data.items && data.items.length > 0) {
      this.allocationData.details = data.items;
    }
  }
  
  // 生成操作记录
  generateOperationLogs(data: any): void {
    this.operationLogs = [
      {
        operationType: '创建',
        operator: data.singer || '李敏',
        operationTime: data.creationTime || new Date(),
        details: '创建了调拨单'
      }
    ];
    
    // 如果有审核记录，添加审核记录
    if (data.status && data.status !== '草稿') {
      this.operationLogs.push({
        operationType: '审核',
        operator: data.auditor || '王经理',
        operationTime: data.auditTime || new Date(Date.now() - 24 * 60 * 60 * 1000),
        details: `审核状态变更为: ${data.status}`
      });
    }
  }
  
  // 直接加载模拟出入库记录数据
  loadMockWarehouseRecords(data: any): void {
    // 模拟出库记录
    const mockOutRecords = [
      {
        recordNo: 'CK202310270001',
        warehouseName: data.fromWarehouse || '仓库一',
        recordDate: new Date(Date.now() - 20 * 60 * 60 * 1000), // 出库时间比审核时间晚4小时
        operator: '张明',
        status: '已完成',
        details: [
          { id: 1, productName: '商品A', productCode: 'P001', specification: '规格1', unit: '个', quantity: 10, unitPrice: 100, amount: 1000, remarks: '调拨出库' },
          { id: 2, productName: '商品B', productCode: 'P002', specification: '规格2', unit: '件', quantity: 5, unitPrice: 200, amount: 1000, remarks: '调拨出库' }
        ]
      },
      {
        recordNo: 'CK202310270002',
        warehouseName: data.fromWarehouse || '仓库一',
        recordDate: new Date(Date.now() - 16 * 60 * 60 * 1000), // 出库时间比审核时间晚4小时
        operator: '李明',
        status: '已完成',
        details: [
          { id: 1, productName: '商品C', productCode: 'P003', specification: '规格3', unit: '箱', quantity: 2, unitPrice: 300, amount: 600, remarks: '调拨出库' }
        ]
      }
    ];
    this.outRecords = mockOutRecords;

    // 模拟入库记录
    const mockInRecords = [
      {
        recordNo: 'RK202310270001',
        warehouseName: data.toWarehouse || '仓库三',
        recordDate: new Date(Date.now() - 16 * 60 * 60 * 1000), // 入库时间比出库时间晚4小时
        operator: '王经理',
        status: '已完成',
        details: [
          { id: 1, productName: '商品A', productCode: 'P001', specification: '规格1', unit: '个', quantity: 10, unitPrice: 100, amount: 1000, remarks: '调拨入库' },
          { id: 2, productName: '商品B', productCode: 'P002', specification: '规格2', unit: '件', quantity: 5, unitPrice: 200, amount: 1000, remarks: '调拨入库' }
        ]
      },
      {
        recordNo: 'RK202310270002',
        warehouseName: data.toWarehouse || '仓库三',
        recordDate: new Date(Date.now() - 12 * 60 * 60 * 1000), // 入库时间比出库时间晚4小时
        operator: '赵经理',
        status: '已完成',
        details: [
          { id: 1, productName: '商品C', productCode: 'P003', specification: '规格3', unit: '箱', quantity: 2, unitPrice: 300, amount: 600, remarks: '调拨入库' }
        ]
      }
    ];
    this.inRecords = mockInRecords;
  }

  // 生成随机单号
  generateRandomNo(): string {
    const now = new Date();
    const year = now.getFullYear().toString().slice(2);
    const month = (now.getMonth() + 1).toString().padStart(2, '0');
    const day = now.getDate().toString().padStart(2, '0');
    const random = Math.floor(Math.random() * 10000).toString().padStart(4, '0');
    return `${year}${month}${day}${random}`;
  }

  // 获取文件扩展名
  getFileExtension(filename: string): string {
    return filename.split('.').pop()?.toLowerCase() || '';
  }
  
  // 生成符合System.Guid格式的UUID
  generateUUID(): string {
    return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
      const r = Math.random() * 16 | 0;
      const v = c === 'x' ? r : (r & 0x3 | 0x8);
      return v.toString(16);
    });
  }
  
  // 验证是否为有效的Guid格式
  isValidGuid(id: string): boolean {
    if (!id) return false;
    const guidRegex = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
    return guidRegex.test(id);
  }

  // 切换标签页
  changeTab(tabName: string): void {
    this.activeTab = tabName;
  }

  // 获取状态标签颜色
  getStatusColor(status: string): string {
    switch (status) {
      case '草稿':
        return 'blue';
      case '待审核':
        return 'orange';
      case '已审核':
        return 'green';
      case '已完成':
        return 'green';
      default:
        return 'default';
    }
  }

  // 获取状态徽章样式类
  getStatusBadgeClass(status: string): string {
    switch (status) {
      case '草稿':
        return 'bg-primary';
      case '待审核':
        return 'bg-warning';
      case '驳回':
        return 'bg-danger';
      case '已审核':
      case '通过':
        return 'bg-success';
      case '已完成':
        return 'bg-success';
      default:
        return 'bg-secondary';
    }
  }

  // 获取文件图标
  getFileIcon(fileType: string): string {
    if (fileType.includes('pdf')) {
      return 'fa-file-pdf';
    } else if (fileType.includes('doc')) {
      return 'fa-file-word';
    } else if (fileType.includes('xls')) {
      return 'fa-file-excel';
    } else if (fileType.includes('jpg') || fileType.includes('png') || fileType.includes('image')) {
      return 'fa-file-image';
    } else {
      return 'fa-file';
    }
  }

  // 编辑调拨单
  editAllocation(): void {
    // 将当前调拨单数据存储到localStorage中，用于编辑页面反填
    localStorage.setItem('editAllocationData', JSON.stringify(this.allocationData));
    // 跳转到编辑页面
    this.router.navigate(['/business/inventory/allocation/edit', this.allocationData.id]);
  }

  // 返回上一页
  goBack(): void {
    this.router.navigate(['/inventory/allocation']);
  }

  // 审核调拨单
  auditAllocation(): void {
    // 实际项目中应该调用API进行审核
    this.message.success('审核操作成功');
  }

  // 复制调拨单
  copyAllocation(): void {
    // 实际项目中应该实现复制逻辑
    this.message.success('复制调拨单成功');
  }

  // 打印调拨单
  printAllocation(): void {
    window.print();
  }

  // 计算总数量
  getTotalQuantity(): number {
    if (!this.allocationData.details || this.allocationData.details.length === 0) {
      return 0;
    }
    
    return this.allocationData.details.reduce((sum: number, item: any) => sum + (Number(item.allocationQuantity) || 0), 0);
  }

  // 计算总金额
  getTotalAmount(): number {
    if (!this.allocationData.details || this.allocationData.details.length === 0) {
      return 0;
    }
    
    return this.allocationData.details.reduce((sum: number, item: any) => sum + (Number(item.allocationAmount) || 0), 0);
  }
} 